<?php
namespace app\data_magic\controller;

use cmf\controller\BaseController;
use think\Db;


class TestController extends BaseController
{
    public function doReadDefinition()
    {
        $table_name=input("table_name");
        if(!$table_name){
            $this->error("数据表名称不能为空");
        }
        $config=config("database");
        $database_name=$config["database"];
        $config["database"]="information_schema";
        $db=Db::connect($config);
        $table_data=$db->table("TABLES")->where(["TABLE_SCHEMA"=>$database_name,"TABLE_NAME"=>$table_name])->find();
        if(!$table_name){
            $this->error("指定数据表不存在");
        }
        var_dump($table_data);
        $fields=$db->table("COLUMNS")->where(["TABLE_SCHEMA"=>$database_name,"TABLE_NAME"=>$table_name])->select();
        var_dump($fields);
    }
    public function doCreateRecord()
    {
        $table_name=input("table_name");
        if(!$table_name){
            $this->error("数据表名称不能为空");
        }
        $config=config("database");
        $database_name=$config["database"];
        $schema=$config;
        $schema["database"]="information_schema";
        $schema_db=Db::connect($schema);
        $table_data=$schema_db->table("TABLES")->where(["TABLE_SCHEMA"=>$database_name,"TABLE_NAME"=>$table_name])->find();
        if(!$table_name){
            $this->error("指定数据表不存在");
        }
        $fields=$schema_db->table("COLUMNS")->where(["TABLE_SCHEMA"=>$database_name,"TABLE_NAME"=>$table_name])->select();

        $db=Db::connect($config);
        $record=$db->table("dm_table")->where(["name"=>$table_name])->find(); //$db->query("SHOW TABLES LIKE '$table_name'");
        if($record){
            $this->error("记录已存在");
        }
        $table=[
            "name"=>$table_name,
            "title"=>$table_data["TABLE_COMMENT"],
            "describe"=>$table_data["TABLE_COMMENT"],
            "primary_key_field"=>""
        ];
        $table_id=$db->table("dm_table")->insertGetId($table);
        if(!$table_id){
            $this->error("插入数据表失败");
        }
        $primary_key_field="";
        $field_list=[];
        foreach($fields as $field){
            if($field["COLUMN_KEY"]==="PRI"){
                $primary_key_field=$field["COLUMN_NAME"];
            }
            $field_list[]=[
                "table_id"=>$table_id,
                "name"=>$field["COLUMN_NAME"],
                "alias"=>"",
                "title"=>$field["COLUMN_COMMENT"],
                "describe"=>$field["COLUMN_COMMENT"],
                "data_type"=>$field["DATA_TYPE"],
                "max_length"=>$field["CHARACTER_MAXIMUM_LENGTH"],
                "is_nullable"=>$field["IS_NULLABLE"]==="YES",
                "type"=>"",
                "type_params"=>"",
            ];
        }
        $db->table("dm_field")->insertAll($field_list);
        $db->execute("UPDATE ");
    }
}
